import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import store from '@/store'
import { parseTime } from '@/utils/util'

const getFile = (url, errorMsg, message) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer',
    })
      .then((data) => {
        resolve(data.data)
      })
      .catch((error) => {
        message.error(errorMsg)
        reject(error.toString())
      })
  })
}
const handleBatchDownload = (data, formData, options) => {
  const { message } = options
  store.state.setting.loading = true
  // const data = ['各类地址1', '各类地址2'] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
  const zip = new JSZip()
  const cache = {}
  const promises = []
  data.forEach((item) => {
    const promise = getFile(
      item.filePath,
      `文件名【${item.fileName}】下载失败`,
      message
    ).then((data) => {
      // 下载文件, 并存成ArrayBuffer对象
      const file_name = item.fileName + '.bin' // 获取文件名
      zip.file(file_name, data, { binary: true }) // 逐个添加文件
      cache[file_name] = data
    })
    promises.push(promise)
  })
  Promise.all(promises)
    .then(() => {
      zip
        .generateAsync({ type: 'blob' })
        .then((content) => {
          // 生成二进制流
          FileSaver.saveAs(
            content,
            `${formData.deviceSN || '下载文件'}(${parseTime(new Date())}).zip`
          ) // 利用file-saver保存文件
        })
        .finally(() => {
          store.state.setting.loading = false
        })
    })
    .catch(() => {
      store.state.setting.loading = false
    })
}

const handleDownload = (item, options) => {
  const { message } = options
  store.state.setting.loading = true
  getFile(item.filePath, '源文件异常,下载失败', message)
    .then((data) => {
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', `${item.fileName}.bin`) // 指定下载后的文件名，防跳转
      document.body.appendChild(link)
      link.click()
    })
    .finally(() => {
      store.state.setting.loading = false
    })
}
export { handleBatchDownload, handleDownload }
